package com.ingenio.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import com.ingenio.business.Rubro;
import com.ingenio.business.SubRubro;
import com.ingenio.dao.RubroAdapter;

/**
 * Servlet implementation class DevolverPrecioServlet
 */
@WebServlet("/DevolverSubRubros")
public class DevolverSubRubrosServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DevolverSubRubrosServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Integer idRubro = Integer.parseInt(request.getParameter("idRubro"));
		RubroAdapter ra = new RubroAdapter();
		JSONObject json = new JSONObject();
		try {
			Rubro r = ra.devolverRubro(idRubro);
			if (r != null){
				JSONArray jaSubRub = new JSONArray();
				List<SubRubro> subrubros = r.getSubrubros();
				for (SubRubro sr: subrubros){
					JSONObject jSubRubros = new JSONObject();
					jSubRubros.put("id", sr.getIdSubRubro());
					jSubRubros.put("desc", sr.getDecSubRubro());
					jaSubRub.put(jSubRubros);
				}
				json.put("subrubros", jaSubRub);
			}else{
				json.put("error",true);
			}
			response.setContentType("application/json");
			response.getWriter().write(json.toString());	
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
